package com.br.fsm.projectdelivery.repositorio;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

import com.br.fsm.projectdelivery.activity.R;
import com.br.fsm.projectdelivery.excecao.RepositorioException;
import com.br.fsm.projectdelivery.util.Constantes;
import com.br.fsm.projectdelivery.util.SQLiteHelper;

public class RepositorioBasico implements IRepositorioBasico {
	
	protected static Context context;
	private static RepositorioBasico instance;
	
	private static final String DATABASE_NAME = "project_delivery";
	private static final int DATABASE_VERSION = 1;	
	
	protected SQLiteDatabase db;
	private SQLiteHelper dbHelper;
	
	private void openDatabase() {
		try {
			closeDatabase();
				
			dbHelper = new SQLiteHelper(context, DATABASE_NAME, DATABASE_VERSION,
					DBScript.SCRIPT_DATABASE_CREATE, DBScript.SCRIPT_DATABASE_DELETE);
			
			db = dbHelper.getWritableDatabase();
		} catch (RepositorioException e) {
			e.printStackTrace();
			Log.e( Constantes.CATEGORIA, e.getMessage());
		}
	}
	
	public static void setContext(Context c){
		context = c;
	}
	
	public void closeDatabase() throws RepositorioException{
		if (db != null) {
			try {
				db.close();
			} catch (SQLException sqe) {
				sqe.printStackTrace();
				Log.e( Constantes.CATEGORIA, sqe.getMessage());
				throw new RepositorioException(context.getResources().getString(
					R.string.db_error));
			}
		}
	}
	
	protected RepositorioBasico(){
		super();
		openDatabase();
	}
	
	public static RepositorioBasico getInstance(){
		if(instance == null){
			instance = new RepositorioBasico();
		}		
		return instance;
	}
	
	public static boolean checkDataBase() {
	    SQLiteDatabase checkDB = null;
	    try {
	        checkDB = SQLiteDatabase.openDatabase( 
	        		"data/data/com.br.fsm.projectdelivery/databases/"+DATABASE_NAME, 
	        		null,
	                SQLiteDatabase.OPEN_READONLY);
	        checkDB.close();
	    } catch (SQLiteException e) {
	    	Log.d(Constantes.CATEGORIA, "Base de dados inexistente");
	    }
	    return checkDB != null ? true : false;
	}	
	
	public void deleteDatabase() {
		dbHelper.close();
		db.close();
		if (context.deleteDatabase(DATABASE_NAME)) {
			Log.d(Constantes.CATEGORIA, "deleteDatabase(): Base deletada.");
		} else {
			Log.d(Constantes.CATEGORIA, "deleteDatabase(): Base não deletada.");
		}
	}
}
